<template>
	<view class="container">
		<view class="header">
			<text class="gradient-title">悟了么</text>
			<view class="score-container">
				<text class="score">{{ state.score }}</text>
				<text class="description">功德</text>
			</view>
		</view>
		<view class="cc-btn-wrap">
			<view @tap="toggleBgSound" :class="['btn-ico', 'btn-sound', state.bgSound.active ?'':'active']">声音
			</view>
			<view @tap="toggleVibrate" :class="['btn-ico', 'btn-vibrate', state.vibrate.active ? '': 'active' ]">振动
			</view>
			<view @tap="autoKnock" :class="['btn-ico', 'btn-auto', state.autoKnocked.enable ? 'active' : '']">
				自动
			</view>
		</view>
		<view class="fish-hammer-container" @click="hitFish">
			<image :src="state.fishImage" class="fish" :class="{ 'fish-hit': state.isFishHit }"></image>
			<image :src="state.hammerImage" class="hammer" id="hammer" :class="{ 'hammer-hit': state.isHammerHit }">
			</image>
			<text class="gongde-display" id="gongdeDisplay" :class="{ 'gongde-show': state.isGongdeShow }">功德+1</text>
		</view>
		<view class="footer">
			轻敲木鱼，领悟人生真谛！
		</view>
	</view>
</template>

<script setup lang="ts">
	import { reactive, onMounted, ref } from "vue";

	const interstitialAd = ref(null);
	let rewardedVideoAd = null;// 广告实例
	const state = reactive({
		score: 0, //敲木鱼次数
		fishImage: '/static/muyu.png',//木鱼图片
		hammerImage: '/static/muyu_chuizi.png',//锤子
		soundUrl: '/static/qiaomuyu.mp3',//敲击声音
		isFishHit: false,//木鱼被敲击
		isHammerHit: false,//锤子敲击
		isGongdeShow: false,//显示功德
		innerAudioContext: null,//播放音频
		bgSound: {//声音开关
			active: true
		},
		vibrate: {//震动开关
			active: true
		},
		autoKnocked: {//自动敲击
			enable: false,
			timer: null,
			speed: 800,
			times: 666,
			unlimited: true,
			current: 0
		},

		audio: null,

		settings: {
			muyu: '',
			gu: '',
			adIsOpen: true,
			chaPingAdId: '',
			videoAdId: '' //广告单元ID
		},
	});

	onMounted(async () => {
		// 小程序环境
		if (typeof uni?.createInnerAudioContext === 'function') {
			console.log('小程序环境')
			state.innerAudioContext = uni.createInnerAudioContext();
			state.innerAudioContext.src = state.soundUrl;
			state.innerAudioContext.loop = false;
		}

		else if (typeof Audio !== 'undefined') {
			console.log('H5 环境')
			state.audio = new Audio(state.soundUrl);
			state.audio.loop = false;
		}
	})

	const hitFish = () => {
		if (state.innerAudioContext && state.bgSound.active) {
			//播放声音
			console.log('播放声音')
			state.innerAudioContext.seek(0);
			state.innerAudioContext.play();
		}
		else console.log('无声音')

		//震动
		if (state.vibrate.active) {
			uni.vibrateShort();
		}

		// 启动动画
		state.isFishHit = true;
		state.isHammerHit = true;
		state.isGongdeShow = true;

		//延迟后停止动画
		setTimeout(() => {
			state.isFishHit = false;
			state.isHammerHit = false;
			state.isGongdeShow = false;
		}, 150);

		state.score++;
	}

	// 声音 开关
	const toggleBgSound = () => {
		state.bgSound.active = !state.bgSound.active
	}

	//震动 开关
	const toggleVibrate = () => {
		state.vibrate.active = !state.vibrate.active
	}

	const autoKnock = () => {
		// 如果已经是自动敲击状态，则停止
		if (state.autoKnocked.enable) {
			stopAutoKnock();
			return;
		}

		// 创建激励视频广告
		if (uni.createRewardedVideoAd) {
			console.log('广告')
			rewardedVideoAd = uni.createRewardedVideoAd({
				adUnitId: state.settings.videoAdId
			});

			// 广告事件监听
			rewardedVideoAd.onLoad(() => {

			});

			// 广告播放错误处理：
			rewardedVideoAd.show().catch(() => {
				rewardedVideoAd
					.load()
					.then(() => rewardedVideoAd.show())
					.catch((err) => {
						autoKnockHandle();
					});
			});

			rewardedVideoAd.onClose((res) => {
				// 用户点击了【关闭广告】按钮 判断用户是否完整观看广告
				if (res && res.isEnded) {
					// 正常播放结束，可以下发游戏奖励
					uni.setStorageSync('lastAdTime', new Date().getTime());
					autoKnockHandle();
				} else {
					uni.showToast({
						title: '未观看结束，无法自动'
					});
					// 播放中途退出，不下发游戏奖励
				}
			});

			// 广告错误事件
			rewardedVideoAd.onError((err) => {

			});
		} else {
			console.log('广告加载失败')
			autoKnockHandle();
		}
	}

	// 自动敲击处理
	const autoKnockHandle = () => {
		// 切换自动敲击状态
		state.autoKnocked.enable = true;
		const intervalCallback = () => {
			if (state.autoKnocked.enable) {
				hitFish();
				console.log('自动敲击中...')
			}
		};

		// 清除之前的定时器（如果有）
		if (state.autoKnocked.timer) {
			clearInterval(state.autoKnocked.timer);
		}

		// 设置新的定时器
		state.autoKnocked.timer = setInterval(intervalCallback, state.autoKnocked.speed);
	};

	// 停止自动敲击
	const stopAutoKnock = () => {
		// 停止定时器
		if (state.autoKnocked.timer) {
			clearInterval(state.autoKnocked.timer);
			state.autoKnocked.timer = null;
		}

		// 更新状态
		state.autoKnocked.enable = false;
		state.autoKnocked.current = 0;

		// 释放广告资源
		if (rewardedVideoAd) {
			rewardedVideoAd.offLoad();
			rewardedVideoAd.offClose();
			rewardedVideoAd.offError();
			rewardedVideoAd = null;
		}

		console.log('已停止自动敲击');
	};
</script>

<style>
	.container {
		background-color: #121212;
		color: #FFFFFF;
	
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
		height: 100vh;
	}

	.header {
		text-align: center;
		position: relative;
		top: 100rpx;
	}

	.header .gradient-title {
		font-size: 25vw;
		
		background: linear-gradient(180deg, rgba(255, 176, 103, 0.05), rgba(115, 55, 0, 0.02));
		-webkit-background-clip: text;
		-webkit-text-fill-color: transparent;
		margin: 0;
	}

	.header .score-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 40rpx;
	}

	.header .score-container .score {
		font-size: 100rpx;
		font-weight: 900;
	}

	.header .score-container .description {
		font-size: 50rpx;
	}

	.fish-hammer-container {
		position: relative;
		cursor: pointer;
		margin-top: 200rpx;
	}

	.fish-hammer-container .fish {
		width: 284rpx;
		height: 236rpx;
		transition: transform 0.1s ease-in-out;
	}

	.fish-hammer-container .fish.fish-hit {
		transform: scale(1.1);
	}

	.fish-hammer-container .hammer {
		position: absolute;
		right: -60rpx;
		top: -40rpx;
		width: 119rpx;
		height: 69rpx;
		transform-origin: bottom left;
		transition: transform 0.1s ease-in-out;
	}

	.fish-hammer-container .hammer.hammer-hit {
		transform: rotate(-25deg);
	}

	.fish-hammer-container .gongde-display {
		position: absolute;
		
		font-size: 30rpx;
		opacity: 0;
		transform: translateY(-20rpx);
		transition: opacity 0.4s ease-out, transform 0.4s ease-out;
	}

	.fish-hammer-container .gongde-display.gongde-show {
		opacity: 1;
		transform: translateY(-40rpx);
	}

	.footer {
		font-size: 24rpx;
		margin-bottom: 100rpx;
	}

	.btn-ico {
		font-size: 20rpx;
		padding-top: 50rpx;
		text-align: center;
	}

	.btn-sound {
		background: 50% 0 url('/static/sound.png') no-repeat;
		background-size: 42rpx 40rpx;
		height: 30rpx;
		position: fixed;
		right: 30rpx;
		top: 150rpx;
		width: 50rpx;
	}

	.btn-sound.active {
		background-image: url('/static/soundclose.png');
		background-size: 42rpx 40rpx;
		width: 50rpx;
	}

	.btn-vibrate {
		background: 50% 0 url('/static/vibrate.png') no-repeat;
		background-size: 42rpx 40rpx;
		height: 40rpx;
		position: fixed;
		right: 30rpx;
		top: 260rpx;
		width: 50rpx;
	}

	.btn-vibrate.active {
		background-image: url('/static/vibrateclose.png');
		background-size: 42rpx 40rpx;
		width: 50rpx;

	}

	.btn-auto {
		background: 50% 0 url('/static/auto.png') no-repeat;
		height: 40rpx;
		position: fixed;
		right: 30rpx;
		top: 370rpx;
	}

	.btn-auto,
	.btn-auto.active {
		background-size: 42rpx 40rpx;
		width: 50rpx;
	}

	.btn-auto.active {
		background-image: url('/static/autoclose.png');
	}
</style>